<!DOCTYPE html>
<html>

<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
<title>douban v3</title>


<style type="text/css">
*{margin:0;padding:0;}
body {
	font:13.34px helvetica,arial,freesans,clean,sans-serif;
	color:black;
	line-height:1.4em;
	background-color: #F8F8F8;
	padding: 0.7em;
}
p {
	margin:1em 0;
	line-height:1.5em;
}
table {
	font-size:inherit;
	font:100%;
	margin:1em;
}
table th{border-bottom:1px solid #bbb;padding:.2em 1em;}
table td{border-bottom:1px solid #ddd;padding:.2em 1em;}
input[type=text],input[type=password],input[type=image],textarea{font:99% helvetica,arial,freesans,sans-serif;}
select,option{padding:0 .25em;}
optgroup{margin-top:.5em;}
pre,code{font:12px Monaco,"Courier New","DejaVu Sans Mono","Bitstream Vera Sans Mono",monospace;}
pre {
	margin:1em 0;
	font-size:12px;
	background-color:#eee;
	border:1px solid #ddd;
	padding:5px;
	line-height:1.5em;
	color:#444;
	overflow:auto;
	-webkit-box-shadow:rgba(0,0,0,0.07) 0 1px 2px inset;
	-webkit-border-radius:3px;
	-moz-border-radius:3px;border-radius:3px;
}
pre code {
	padding:0;
	font-size:12px;
	background-color:#eee;
	border:none;
}
code {
	font-size:12px;
	background-color:#f8f8ff;
	color:#444;
	padding:0 .2em;
	border:1px solid #dedede;
}
img{border:0;max-width:100%;}
abbr{border-bottom:none;}
a{color:#4183c4;text-decoration:none;}
a:hover{text-decoration:underline;}
a code,a:link code,a:visited code{color:#4183c4;}
h2,h3{margin:1em 0;}
h1,h2,h3,h4,h5,h6{border:0;}
h1{font-size:170%;border-top:4px solid #aaa;padding-top:.5em;margin-top:1.5em;}
h1:first-child{margin-top:0;padding-top:.25em;border-top:none;}
h2{font-size:150%;margin-top:1.5em;border-top:4px solid #e0e0e0;padding-top:.5em;}
h3{margin-top:1em;}
hr{border:1px solid #ddd;}
ul{margin:1em 0 1em 2em;}
ol{margin:1em 0 1em 2em;}
ul li,ol li{margin-top:.5em;margin-bottom:.5em;}
ul ul,ul ol,ol ol,ol ul{margin-top:0;margin-bottom:0;}
blockquote{margin:1em 0;border-left:5px solid #ddd;padding-left:.6em;color:#555;}
dt{font-weight:bold;margin-left:1em;}
dd{margin-left:2em;margin-bottom:1em;}
sup {
    font-size: 0.83em;
    vertical-align: super;
    line-height: 0;
}
kbd {
  display: inline-block;padding: 3px 5px;font-size: 11px;line-height: 10px;color: #555;vertical-align: middle;background-color: #fcfcfc;border: solid 1px #ccc;border-bottom-color: #bbb;border-radius: 3px;box-shadow: inset 0 -1px 0 #bbb;
}
* {
	-webkit-print-color-adjust: exact;
}
@media screen and (min-width: 914px) {
    body {
        width: 854px;
        margin:0 auto;
    }
}
@media print {
	table, pre {
		page-break-inside: avoid;
	}
	pre {
		word-wrap: break-word;
	}
}
</style>

<style type="text/css">
/**
 * prism.js default theme for JavaScript, CSS and HTML
 * Based on dabblet (http://dabblet.com)
 * @author Lea Verou
 */

code[class*="language-"],
pre[class*="language-"] {
	color: black;
	background: none;
	text-shadow: 0 1px white;
	font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
	text-align: left;
	white-space: pre;
	word-spacing: normal;
	word-break: normal;
	word-wrap: normal;
	line-height: 1.5;

	-moz-tab-size: 4;
	-o-tab-size: 4;
	tab-size: 4;

	-webkit-hyphens: none;
	-moz-hyphens: none;
	-ms-hyphens: none;
	hyphens: none;
}

pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
	text-shadow: none;
	background: #b3d4fc;
}

pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
code[class*="language-"]::selection, code[class*="language-"] ::selection {
	text-shadow: none;
	background: #b3d4fc;
}

@media print {
	code[class*="language-"],
	pre[class*="language-"] {
		text-shadow: none;
	}
}

/* Code blocks */
pre[class*="language-"] {
	padding: 1em;
	margin: .5em 0;
	overflow: auto;
}

:not(pre) > code[class*="language-"],
pre[class*="language-"] {
	background: #f5f2f0;
}

/* Inline code */
:not(pre) > code[class*="language-"] {
	padding: .1em;
	border-radius: .3em;
	white-space: normal;
}

.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
	color: slategray;
}

.token.punctuation {
	color: #999;
}

.namespace {
	opacity: .7;
}

.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
	color: #905;
}

.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
	color: #690;
}

.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
	color: #a67f59;
	background: hsla(0, 0%, 100%, .5);
}

.token.atrule,
.token.attr-value,
.token.keyword {
	color: #07a;
}

.token.function {
	color: #DD4A68;
}

.token.regex,
.token.important,
.token.variable {
	color: #e90;
}

.token.important,
.token.bold {
	font-weight: bold;
}
.token.italic {
	font-style: italic;
}

.token.entity {
	cursor: help;
}
</style>


</head>

<body>

<p>参考代码：<a href="http://git.oschina.net/crossin/crawler/blob/master/ex4_douban_cast_v1.py" target="_blank">http://git.oschina.net/crossin/crawler/blob/master/ex4_douban_cast_v1.py</a></p>

<h2 id="toc_0">1. PyMongo 的增删改查</h2>

<p>增删改查（CRUD）是数据库最基本的操作。通过 PyMongo 提供的接口可以直接对 MongoDB 中的数据进行操作。</p>

<h3 id="toc_1">插入</h3>

<p>插入单条数据：</p>

<div><pre><code class="language-python">insert_one(document, bypass_document_validation=False)</code></pre></div>

<p><strong>document</strong> 带插入的文档，默认会自动加上 <code>_id</code> 属性</p>

<p><strong>bypass<em>document</em>validation</strong> 是否绕过文档验证</p>

<p>插入多条数据：</p>

<div><pre><code class="language-python">insert_many(documents, ordered=True, bypass_document_validation=False)</code></pre></div>

<p><strong>ordered</strong> 是否按顺序插入</p>

<p>示例：</p>

<div><pre><code class="language-python">&gt;&gt;&gt; db = client.test_db
&gt;&gt;&gt; a = db.test_data.insert_one({&#39;name&#39;: &#39;Mike&#39;, &#39;age&#39;: 18})
&gt;&gt;&gt; a.inserted_id
ObjectId(&#39;...&#39;)

&gt;&gt;&gt; new_data = [{&#39;name&#39;: &#39;Jim&#39;, &#39;age&#39;: 19}, {&#39;name&#39;: &#39;Ken&#39;, &#39;age&#39;: 20}]
&gt;&gt;&gt; results = db.test_data.insert_many(new_data)
&gt;&gt;&gt; results.inserted_ids
[ObjectId(&#39;...&#39;), ObjectId(&#39;...&#39;)]</code></pre></div>

<h3 id="toc_2">查找</h3>

<p>查找多条数据：</p>

<div><pre><code class="language-python">find(filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE, sort=None, allow_partial_results=False, oplog_replay=False, modifiers=None, manipulate=True) </code></pre></div>

<p><strong>filter</strong> 查询筛选条件，字典类型，不设置则查询所有文档</p>

<p>查找单条数据：</p>

<div><pre><code class="language-python">find_one(filter=None, *args, **kwargs)</code></pre></div>

<p>find 的参数均适用于 find_one。</p>

<p>示例：</p>

<div><pre><code class="language-python">&gt;&gt;&gt; for data in db.test_data.find():
...     print(data)
{u&#39;age&#39;: 18, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Mike&#39;}
{u&#39;age&#39;: 19, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Jim&#39;}
{u&#39;age&#39;: 20, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Ken&#39;}

&gt;&gt;&gt; db.test_data.find_one({&#39;name&#39;: &#39;Ken&#39;})
{u&#39;age&#39;: 20, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Ken&#39;}</code></pre></div>

<h3 id="toc_3">更新</h3>

<p>更新一条数据：</p>

<div><pre><code class="language-python">update_one(filter, update, upsert=False, bypass_document_validation=False, collation=None)</code></pre></div>

<p><strong>update</strong> 更新的具体方式，见后文 <strong>更新操作符</strong>
<strong>upsert</strong> 设为 True 时，如果没有对应文档，则插入一条新数据</p>

<p>更新多条数据：</p>

<div><pre><code class="language-python">update_many(filter, update, upsert=False, bypass_document_validation=False, collation=None)</code></pre></div>

<p>示例：</p>

<div><pre><code class="language-python">&gt;&gt;&gt; result = db.test_data.update({&#39;name&#39;: &#39;Mike&#39;}, {&#39;$set&#39;: {&#39;age&#39;: 17}})
&gt;&gt;&gt; result. matched_count
1
&gt;&gt;&gt; result.modified_count
1

&gt;&gt;&gt; result = db.test_data.update({}, {&#39;$inc&#39;: {&#39;age&#39;: 2}})
&gt;&gt;&gt; for data in db.test_data.find():
...     print(data)
{u&#39;age&#39;: 19, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Mike&#39;}
{u&#39;age&#39;: 21, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Jim&#39;}
{u&#39;age&#39;: 22, u&#39;_id&#39;: ObjectId(&#39;...&#39;), u&#39;name&#39;: u&#39;Ken&#39;}</code></pre></div>

<h3 id="toc_4">删除</h3>

<p>删除一条数据：</p>

<div><pre><code class="language-python">delete_one(filter, collation=None)</code></pre></div>

<p>删除多条数据：</p>

<div><pre><code class="language-python">delete_one(filter, collation=None)</code></pre></div>

<p>示例：</p>

<div><pre><code class="language-python">&gt;&gt;&gt; db.test_data.count()
3
&gt;&gt;&gt; result = db.test_data.delete_one({&#39;name&#39;: &#39;Mike&#39;})
&gt;&gt;&gt; result.delete_count
1
&gt;&gt;&gt; db.test_data.count()
2
&gt;&gt;&gt; result = db.test_data.delete_many()
&gt;&gt;&gt; db.test_data.count()
0</code></pre></div>

<h3 id="toc_5">参考资料</h3>

<ol>
<li><a href="http://api.mongodb.com/python/current/tutorial.html" target="_blank">入门教程 - PyMongo 官方文档</a></li>
<li><a href="http://api.mongodb.com/python/current/api/pymongo/collection.html" target="_blank">collection - PyMongo 官方文档</a></li>
<li><a href="https://zhuanlan.zhihu.com/p/20500518" target="_blank">pymongo的简单使用 - 林骏翔</a></li>
</ol>

<h2 id="toc_6">2. MongoDB 更新操作符</h2>

<p>在 MongoDB 的更新语句中，需要通过<strong>更新操作符</strong>来指明更新的方式。</p>

<p>常用操作符：</p>

<table>
<thead>
<tr>
<th style="text-align: center">操作符</th>
<th style="text-align: left">说明</th>
</tr>
</thead>

<tbody>
<tr>
<td style="text-align: center">$set</td>
<td style="text-align: left">设置字段值</td>
</tr>
<tr>
<td style="text-align: center">$unset</td>
<td style="text-align: left">删除字段</td>
</tr>
<tr>
<td style="text-align: center">$inc</td>
<td style="text-align: left">增加字段的值</td>
</tr>
<tr>
<td style="text-align: center">$mul</td>
<td style="text-align: left">乘以字段的值</td>
</tr>
<tr>
<td style="text-align: center">$rename</td>
<td style="text-align: left">重命名字段</td>
</tr>
<tr>
<td style="text-align: center">$min</td>
<td style="text-align: left">设定为字段值和设定值的较小值</td>
</tr>
<tr>
<td style="text-align: center">$max</td>
<td style="text-align: left">设定为字段值和设定值的较大值</td>
</tr>
<tr>
<td style="text-align: center">$currentDate</td>
<td style="text-align: left">设置字段为当前时间</td>
</tr>
</tbody>
</table>

<h3 id="toc_7">参考资料</h3>

<ol>
<li><a href="http://www.cnblogs.com/egger/archive/2013/05/15/3053617.html" target="_blank">字段更新操作符 Field Update Operators - Hejin.Wang</a></li>
<li><a href="https://docs.mongodb.com/manual/reference/operator/update/" target="_blank">更新操作符 - PyMongo 官方文档</a></li>
</ol>



<script type="text/javascript">
var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={util:{encode:function(e){return e instanceof a?new a(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).match(/\[object (\w+)\]/)[1]},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++t}),e.__id},clone:function(e){var t=n.util.type(e);switch(t){case"Object":var a={};for(var r in e)e.hasOwnProperty(r)&&(a[r]=n.util.clone(e[r]));return a;case"Array":return e.map&&e.map(function(e){return n.util.clone(e)})}return e}},languages:{extend:function(e,t){var a=n.util.clone(n.languages[e]);for(var r in t)a[r]=t[r];return a},insertBefore:function(e,t,a,r){r=r||n.languages;var l=r[e];if(2==arguments.length){a=arguments[1];for(var i in a)a.hasOwnProperty(i)&&(l[i]=a[i]);return l}var o={};for(var s in l)if(l.hasOwnProperty(s)){if(s==t)for(var i in a)a.hasOwnProperty(i)&&(o[i]=a[i]);o[s]=l[s]}return n.languages.DFS(n.languages,function(t,n){n===r[e]&&t!=e&&(this[t]=o)}),r[e]=o},DFS:function(e,t,a,r){r=r||{};for(var l in e)e.hasOwnProperty(l)&&(t.call(e,l,e[l],a||l),"Object"!==n.util.type(e[l])||r[n.util.objId(e[l])]?"Array"!==n.util.type(e[l])||r[n.util.objId(e[l])]||(r[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,l,r)):(r[n.util.objId(e[l])]=!0,n.languages.DFS(e[l],t,null,r)))}},plugins:{},highlightAll:function(e,t){var a={callback:t,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};n.hooks.run("before-highlightall",a);for(var r,l=a.elements||document.querySelectorAll(a.selector),i=0;r=l[i++];)n.highlightElement(r,e===!0,a.callback)},highlightElement:function(t,a,r){for(var l,i,o=t;o&&!e.test(o.className);)o=o.parentNode;o&&(l=(o.className.match(e)||[,""])[1],i=n.languages[l]),t.className=t.className.replace(e,"").replace(/\s+/g," ")+" language-"+l,o=t.parentNode,/pre/i.test(o.nodeName)&&(o.className=o.className.replace(e,"").replace(/\s+/g," ")+" language-"+l);var s=t.textContent,u={element:t,language:l,grammar:i,code:s};if(!s||!i)return n.hooks.run("complete",u),void 0;if(n.hooks.run("before-highlight",u),a&&_self.Worker){var c=new Worker(n.filename);c.onmessage=function(e){u.highlightedCode=e.data,n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,r&&r.call(u.element),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},c.postMessage(JSON.stringify({language:u.language,code:u.code,immediateClose:!0}))}else u.highlightedCode=n.highlight(u.code,u.grammar,u.language),n.hooks.run("before-insert",u),u.element.innerHTML=u.highlightedCode,r&&r.call(t),n.hooks.run("after-highlight",u),n.hooks.run("complete",u)},highlight:function(e,t,r){var l=n.tokenize(e,t);return a.stringify(n.util.encode(l),r)},tokenize:function(e,t){var a=n.Token,r=[e],l=t.rest;if(l){for(var i in l)t[i]=l[i];delete t.rest}e:for(var i in t)if(t.hasOwnProperty(i)&&t[i]){var o=t[i];o="Array"===n.util.type(o)?o:[o];for(var s=0;s<o.length;++s){var u=o[s],c=u.inside,g=!!u.lookbehind,h=!!u.greedy,f=0,d=u.alias;u=u.pattern||u;for(var p=0;p<r.length;p++){var m=r[p];if(r.length>e.length)break e;if(!(m instanceof a)){u.lastIndex=0;var y=u.exec(m),v=1;if(!y&&h&&p!=r.length-1){var b=r[p+1].matchedStr||r[p+1],k=m+b;if(p<r.length-2&&(k+=r[p+2].matchedStr||r[p+2]),u.lastIndex=0,y=u.exec(k),!y)continue;var w=y.index+(g?y[1].length:0);if(w>=m.length)continue;var _=y.index+y[0].length,P=m.length+b.length;if(v=3,P>=_){if(r[p+1].greedy)continue;v=2,k=k.slice(0,P)}m=k}if(y){g&&(f=y[1].length);var w=y.index+f,y=y[0].slice(f),_=w+y.length,S=m.slice(0,w),O=m.slice(_),j=[p,v];S&&j.push(S);var A=new a(i,c?n.tokenize(y,c):y,d,y,h);j.push(A),O&&j.push(O),Array.prototype.splice.apply(r,j)}}}}}return r},hooks:{all:{},add:function(e,t){var a=n.hooks.all;a[e]=a[e]||[],a[e].push(t)},run:function(e,t){var a=n.hooks.all[e];if(a&&a.length)for(var r,l=0;r=a[l++];)r(t)}}},a=n.Token=function(e,t,n,a,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=a||null,this.greedy=!!r};if(a.stringify=function(e,t,r){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return a.stringify(n,t,e)}).join("");var l={type:e.type,content:a.stringify(e.content,t,r),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:r};if("comment"==l.type&&(l.attributes.spellcheck="true"),e.alias){var i="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(l.classes,i)}n.hooks.run("wrap",l);var o="";for(var s in l.attributes)o+=(o?" ":"")+s+'="'+(l.attributes[s]||"")+'"';return"<"+l.tag+' class="'+l.classes.join(" ")+'" '+o+">"+l.content+"</"+l.tag+">"},!_self.document)return _self.addEventListener?(_self.addEventListener("message",function(e){var t=JSON.parse(e.data),a=t.language,r=t.code,l=t.immediateClose;_self.postMessage(n.highlight(r,n.languages[a],a)),l&&_self.close()},!1),_self.Prism):_self.Prism;var r=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return r&&(n.filename=r.src,document.addEventListener&&!r.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",n.highlightAll)),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism);
</script>

<script type="text/javascript">
Prism.languages.python={"triple-quoted-string":{pattern:/"""[\s\S]+?"""|'''[\s\S]+?'''/,alias:"string"},comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},string:/("|')(?:\\?.)*?\1/,"function":{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_][a-zA-Z0-9_]*(?=\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)[a-z0-9_]+/i,lookbehind:!0},keyword:/\b(?:as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/,"boolean":/\b(?:True|False)\b/,number:/\b-?(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]|\b(?:or|and|not)\b/,punctuation:/[{}[\];(),.:]/};
</script>


</body>

</html>
